<?php

namespace app\admin\controller\community\project;

use app\common\controller\Backend;
use think\Db;

/**
 * 公益课堂项目管理
 *
 * @icon fa fa-heart
 */
class Publicwelfare extends Backend
{
    /**
     * Publicwelfare模型对象
     * @var \app\admin\model\community\project\Publicwelfare
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\community\project\Publicwelfare;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $user=$this->auth->getUserInfo();
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            // 定义搜索字段和排序字段
            $searchFields = ['p.school_name', 'p.project_name', 'c.name', 'p.project_name|p.school_name|c.name'];
            $sortFields = [
                'id' => 'p.id',
                'school_name' => 'p.school_name',
                'project_name' => 'p.project_name',
                'community_name' => 'c.name',
                'createtime' => 'p.createtime',
                'updatetime' => 'p.updatetime',
                'start_time' => 'p.start_time',
                'end_time' => 'p.end_time'
            ];
            
            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 调试日志
            error_log("Publicwelfare Index - city_id: $city_id, school_id: $school_id");

            list($where, $sort, $order, $offset, $limit) = $this->buildparams($sortFields, $searchFields);
            
            $list = $this->model
                ->alias('p')
                ->join('Community c', 'p.community_id = c.id')
                ->field('p.*, c.name as community_name');
                
            // 添加城市和学校过滤
            if (!empty($city_id)) {
                $list = $list->where("p.city_id", "=", $city_id);
            } else if (!empty($school_id)) {
                $list = $list->where("p.school_id", "=", $school_id);
            } else if($user['group_id'] == 8) {
                $list = $list->where('p.community_id', '=', $user['community_id']);
            }
            
            // 搜索条件已由 filter/op 参数和 search 参数处理
            
            // 处理快速搜索
            $search = $this->request->get('search');
            if (!empty($search)) {
                // 快捷搜索框直接搜索多个字段
                $list->where(function ($query) use ($search) {
                    $query->where('p.project_name', 'like', '%' . $search . '%')
                          ->whereOr('p.school_name', 'like', '%' . $search . '%')
                          ->whereOr('c.name', 'like', '%' . $search . '%');
                });
            }
            
            // 处理高级搜索参数
            $filter = $this->request->get('filter', '');
            $op = $this->request->get('op', '');
            
            if ($filter && $op) {
                $filter = (array)json_decode($filter, true);
                $op = (array)json_decode($op, true);
                foreach ($filter as $key => $val) {
                    if ($val) {
                        $operator = isset($op[$key]) ? $op[$key] : 'like';
                        if ($operator == 'like') {
                            $list->where($key, 'like', "%{$val}%");
                        } else {
                            $list->where($key, $operator, $val);
                        }
                    }
                }
            }

            // 添加排序条件
            if ($sort) {
                // 处理排序字段，确保使用正确的表名前缀
                switch ($sort) {
                    case 'id':
                        $list->order('p.id', $order);
                        break;
                    case 'school_name':
                        $list->order('p.school_name', $order);
                        break;
                    case 'project_name':
                        $list->order('p.project_name', $order);
                        break;
                    case 'community_name':
                        $list->order('c.name', $order);
                        break;
                    case 'start_time':
                        $list->order('p.start_time', $order);
                        break;
                    case 'end_time':
                        $list->order('p.end_time', $order);
                        break;
                    case 'createtime':
                        $list->order('p.createtime', $order);
                        break;
                    case 'updatetime':
                        $list->order('p.updatetime', $order);
                        break;
                    default:
                        $list->order('p.id', $order);
                }
            } else {
                $list->order('p.id', 'desc');
            }

            // 执行查询并打印SQL
            $list->fetchSql(false);
            $debug = Db::getLastSql();
            trace("SQL语句: " . $debug, 'debug');
            
            // 执行实际查询
            $list = $list->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $user=$this->auth->getUserInfo();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 如果是社区管理员，自动设置社区ID
                if ($this->auth->group_id == 8) {
                    $params['community_id'] = $user['community_id'];
                }

                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                // 调试日志
                error_log("Publicwelfare Add - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                // 设置学校名称
                $params['school_name'] = $this->auth->school_name;

                // 格式化时间字段
                if (isset($params['start_time'])) {
                    if (is_string($params['start_time'])) {
                        // 如果是字符串，转换为时间戳
                        $params['start_time'] = strtotime($params['start_time']);
                    } elseif (is_numeric($params['start_time'])) {
                        // 如果是数字，保持原样
                        $params['start_time'] = intval($params['start_time']);
                    }
                }
                if (isset($params['end_time'])) {
                    if (is_string($params['end_time'])) {
                        // 如果是字符串，转换为时间戳
                        $params['end_time'] = strtotime($params['end_time']);
                    } elseif (is_numeric($params['end_time'])) {
                        // 如果是数字，保持原样
                        $params['end_time'] = intval($params['end_time']);
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 传递学校名称到视图
        $this->view->assign('school_name', $this->auth->school_name);
        return $this->view->fetch();
    }

    function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUserInfo();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 如果是社区管理员，自动设置社区ID
                if ($this->auth->group_id == 8) {
                    $params['community_id'] = $user['community_id'];
                }

                // 获取当前记录
                $row = $this->model->get($ids);
                
                // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    if (empty($row['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    if (empty($row['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                }
                
                // 调试日志
                error_log("Publicwelfare Edit - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                // 设置学校名称
                $params['school_name'] = $this->auth->school_name;

                // 格式化时间字段
                if (isset($params['start_time'])) {
                    if (is_string($params['start_time'])) {
                        // 如果是字符串，转换为时间戳
                        $params['start_time'] = strtotime($params['start_time']);
                    } elseif (is_numeric($params['start_time'])) {
                        // 如果是数字，保持原样
                        $params['start_time'] = intval($params['start_time']);
                    }
                }
                if (isset($params['end_time'])) {
                    if (is_string($params['end_time'])) {
                        // 如果是字符串，转换为时间戳
                        $params['end_time'] = strtotime($params['end_time']);
                    } elseif (is_numeric($params['end_time'])) {
                        // 如果是数字，保持原样
                        $params['end_time'] = intval($params['end_time']);
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model
                        ->allowField(true)
                        ->save($params, ['id' => $ids]);
                    Db::commit();
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } catch (ValidateException $e) {

                }
            }
        }else{
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            // 传递学校名称到视图
            $this->view->assign('school_name', $this->auth->school_name);
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }

    }
}